package com.hatic.store;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DocumentHandler {
	private Configuration configuration = null;

	public DocumentHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
	}

	/**
	 * 根据freemarker模板生成word文件
	 * @param path  生成的word路径
	 * @param keyids 选择记录的主键值
	 * @return
	 */
	public File createDoc(String path,String[] keyids) {
		//要填入模本的数据文件
		Map<String,Object> dataMap=new HashMap<String,Object>();
		getData(dataMap,keyids);
		//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
		configuration.setClassForTemplateLoading(this.getClass(), "/com/hatic/store");
		Template t=null;
		try {
			//template.ftl为要装载的模板
			t = configuration.getTemplate("template.ftl","UTF-8");
			t.setEncoding("UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		//输出文档路径及名称
		File outFile = new File(path);
		Writer out = null;
		try {
			try {
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
			} catch (UnsupportedEncodingException e) { 
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		 
        try {
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outFile;
	}
	
	/**
	 * 注意dataMap里存放的数据Key值要与模板中的参数相对应
	 * @param dataMap
	 */
	 private void getData(Map<String,Object> dataMap,String[] keyids){
		  List<ProjectStore> _sect = new ArrayList<ProjectStore>();
		  List<Map<String,String>> mlist = new ExpDocBO().getStoreInfo(keyids);
		  for(int i=0; i<mlist.size();i++)
		  {
			  Map map = (Map)mlist.get(i);
			  ProjectStore ps=new ProjectStore();
			  ps.setPlan_name((String)map.get("plan_name"));
			  ps.setDept_name((String)map.get("dept_name"));
			  ps.setPlan_desc((String)map.get("plan_desc"));
			  ps.setProject_background((String)map.get("project_background"));
			  ps.setProject_cause((String)map.get("project_cause"));
			  ps.setProject_estimate((String)map.get("project_estimate"));
			  ps.setProject_result((String)map.get("project_result"));
			  _sect.add(ps);
		  }
		  dataMap.put("sect", _sect);
		  
	  }

	

}
